package com.tiny.persistence.repository.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.ai.web.cache.Constants;
import com.ai.web.cache.UserContext;
import com.ai.web.vo.WxRoleV;
import com.tiny.persistence.domain.WxRole;
import com.tiny.persistence.repository.plus.WxRoleRepoPlus;
/**
 * 微信前端角色仓储实现
* @ClassName: WxRoleRepoImpl 
* @Description: TODO 
* @author:  
* @date: 2014年3月24日
*
 */
public class WxRoleRepoImpl extends BaseRepoImpl<WxRole> implements WxRoleRepoPlus{
    
    private static Logger logger = Logger.getLogger(WxRoleRepoImpl.class);
    
    @Override
    public List<WxRole> getListByCondition(Map<String, Object> condition) {
        
        StringBuffer sqlquery = new StringBuffer();
        sqlquery.append("from WxRole as a where 1=1 ");
        
        //查询条件
        String name = null;
        if(condition.get("name")!=null){
            name = String.valueOf(condition.get("name"));
        }
        if(name!=null){
            sqlquery.append(" and a.name like :name"); 
        }

        Query query = em.createQuery(sqlquery.toString());
        if(name!=null){
            query.setParameter("name", "%"+name+"%");
        }
        
        UserContext uc = (UserContext) condition.get(Constants.USER_CONTEXT);
        query.setFirstResult((Integer) condition.get(Constants.KEY_RECORD_FROM));
        query.setMaxResults(uc.getPageSize());
        List<WxRole> list = query.getResultList();
        
        logger.info("======= " + list);
        
        return list;
    }

    @Override
    public int getCountByCondition(Map<String, Object> condition) {
        
        StringBuffer sqlquery = new StringBuffer();
        sqlquery.append("select count(*) from WxRole as a where 1=1 ");
        
        //查询条件
        String name = null;
        if(condition.get("name")!=null){
            name = String.valueOf(condition.get("name"));
        }
        if(name!=null){
            sqlquery.append(" and a.name like :name"); 
        }

        Query query = em.createQuery(sqlquery.toString());
        if(name!=null){
            query.setParameter("name", "%"+name+"%");
        }
        Object obj = query.getSingleResult();
        
        logger.info("======= count=" + obj);
        
        return Integer.parseInt(obj.toString());
    }

	@SuppressWarnings("unchecked")
	public List<WxRoleV> getRoleList() {
		 Query query = em.createQuery("from WxRole as re");
    	 return query.getResultList();
	}

}
